#!/usr/bin/env python
# -*- coding: utf-8 -*-


####################################################
# Licencse : MIT License
# Please refer to the below page for more specific information
# http://opensource.org/licenses/mit-license.php
#
# Author : namh
# Date : 2012-08-17
#####################################################


import httplib2
import urllib
import codecs
import os
import re
import shutil
import sys

__version__ = '0.9'



def getVolInfo(url):
    '''
    getVolInfo
        visit the first page of the specific volume, then retrieve the
        maximum number of the volume and the url of the file.
    
    @return maxpg
    @return imgurl
    
    '''
    ####################################
    # 1st
    headers = {
            "cache-control":"no-cache",
            "Connection": "keep-alive",
            "accept-encoding":"gzip, deflate",
            "Content-type": "application/x-www-form-urlencoded",
            "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 \
    (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7"
        }

    http = httplib2.Http('.cache')

    response, content = http.request(url,
                            "GET",
                            headers=headers)
    
    
    # DOM making
    from lxml import html
    root = html.fromstring(content)
    
    ########################
    # get the url to retreive pages
    #   some manga page urls are composited of chapter volume
    #   Thus, get the url with the start chapter volume
    #   i.e. http://view.thespectrum.net/manga/Bakuman/Volume%2007/bakuman_c001_020.JPG
    img = root.get_element_by_id('mainimage')
    imgurl = img.get('src')
    
    
    # get the maximum page number
    vls = root.find_class('viewerLabel')
    maxpg = vls[-1].text.rstrip()[-3:]   # treat <div class="viewerLabel"> of 184</div>
    
    return int(maxpg), imgurl
 

    
def getFileFromUrl(url, filename):
    '''
        retrieve and save the pictures from the url{@see:@param url}
        
        @param url : the URL of the file
        @param filename : the name with which the URL will be saved
    '''
    ####################################
    # 1st
    headers = {
            "cache-control":"no-cache",
            "Connection": "keep-alive",
            "accept-encoding":"gzip, deflate",
            "Content-type": "application/x-www-form-urlencoded",
            "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 \
    (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7"
        }

    http = httplib2.Http('.cache')

    response, content = http.request(url,
                            "GET",
                            headers=headers)

    logging.debug("response : %s"%response)
    
    r = response.status
    if r != 404:
        # file not found
        try:
            wf = codecs.open(filename, "wb")
        except IOError:
            print filename + " does not exist"
        else:
            wf.write(content)
            wf.close()

    return r

    
    
def main(argv):
    if len(argv) < 3:
        print 'Usage : run.py [maga_name_with_lower_letter] [vol_num]'
        return
    
    # to logging
    logging.info("test")
    
    # arguments
    volume = int(argv[2])
    manga = argv[1].lower()     # 'bakuman'
    
    manga2 = manga[0].upper() + manga[1:]   # string which has the capital first letter

    host = "http://view.thespectrum.net"
    urlrest = "/series/%s-volume-01.html?ch=Volume+%02d"%(manga,volume)
    
    ########################
    #   getVolInfo()
    #       - get the maximum number of pages
    #       - get the image file url
    max, firstpageurl = getVolInfo(host + urlrest)
    baseurl = firstpageurl[:firstpageurl.rfind('/')+1]
    encurl = urllib.quote(baseurl, '://')  # percentage encoding

    
    ########################
    # determine the way of downloading
    sidx = firstpageurl.rfind('/')
    ss = re.split('[_.]',firstpageurl[sidx:])    # result seems ['/bleach', 'v01', '001', 'jpg']
    
    mode = 'v' if ss[1].find('v') != -1 else 'c'    # s.find('v')!=-1 ? 'v' : 'c"
    ext = ss[3]
    firstpg = int(ss[2])
    if mode == 'v':
        # volume suffix filename is used
        volno = volume
        filenamebase = "%s_v%02d_%03d.%s"
    else:
        # chapter suffix filename is used
        volno = int(ss[1][1:]) # number, for example, '035' out of 'c035'
        filenamebase = "%s_c%03d_%03d.%s"
    
    print 'manga : ', manga
    print 'max page number : ', max
    logging.debug("volno : %d", volume)
    
    
    ########################
    # make a directory
    
    
    # move to current working directory
    
    '''TODO: 
        exefilepath should be __file__ but, because of py2exe, 
        I've changed to "os.path.split(sys.argv[0])[0] "
        
        There might be possible to have an problem.
    '''
    exefilepath = sys.argv[0]
    abspath = os.path.abspath(exefilepath)
    dname = os.path.dirname(abspath)
    os.chdir(dname)
    
    mangadir = "%s_v%02d"%(manga,volume)
    if not os.path.exists(mangadir):
        try:
            os.makedirs(mangadir)
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
                
    # move to just-made directory
    os.chdir(mangadir)
    
    
    ########################
    # downloading
    falseCount = 0
    c = 1
    pg = firstpg # page number, only some cover page has '0' number
    while c <= max :
        filename = filenamebase%(manga,volno,pg,ext)
        url = encurl + filename
        print "%d/%d : %s"%(c, max, url)
        
        if getFileFromUrl(url, filename) == 404:
            # if there is no such a file
            
            # not to retrieve more than 10 times
            if falseCount > 10:
                break;
            else:
                falseCount += 1

            if mode == 'c':
                volno += 1
                pg = 1;
                c -= 1;
            
        else :
            pg += 1
        
        c += 1
        logging.debug("volno : %d / pg : %d / c : %d"%(volno,pg,c))

    ########################
    # Erasing the .cache folder
    if os.path.exists('.cache') is True:
        shutil.rmtree('.cache')
        logging.info(".cache folder is erased")
        
    # move back to origin folder
    os.chdir('..')
    
    

import logging
import optparse

def runLogging(argv):
    LOGGING_LEVELS = {'critical': logging.CRITICAL,
                      'error': logging.ERROR,
                      'warning': logging.WARNING,
                      'info': logging.INFO,
                      'debug': logging.DEBUG}

    parser = optparse.OptionParser()
    parser.add_option('-l', '--logging-level', help='Logging level')
    parser.add_option('-f', '--logging-file', help='Logging file name')
    (options, args) = parser.parse_args(argv)
    logging_level = LOGGING_LEVELS.get(options.logging_level, logging.INFO)
    logging.basicConfig(level=logging_level, filename=options.logging_file,
                      format='%(asctime)s %(levelname)s: %(message)s',
                      datefmt='%Y-%m-%d %H:%M:%S')
                      
    logging.info('logging starts')


if __name__ == "__main__":
    runLogging(sys.argv)
    main(sys.argv)